﻿using System.Data;
using System.Diagnostics;
using System.Threading.Tasks;
using Dapper;
using NLog;
using Oracle.ManagedDataAccess.Client;
using Quartz;
using Raise.Workbench.Service.Models;
using Raise.Workbench.Tools;

namespace Raise.Workbench.Service {
    /// <summary>
    /// 每次执行，都会创建一个新的实例
    /// </summary>
    [DisallowConcurrentExecution]
    public class ExecuteJob : IJob {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger(typeof(QuartzServiceFactory));

        private static IDbConnection Connection {
            get {
                string connString = Utils.GetConnectString();
                return new OracleConnection(connString);
            }
        }

        public Task Execute(IJobExecutionContext context) {
            return Task.Factory.StartNew(() => {
                //获取本次JOB中的唯一标识
                JobDataMap data = context.JobDetail.JobDataMap;
                var uniqueCode = data.GetString(GlobalVar.UNIQUE_CODE);
                using(var con = Connection) {
                    //and status = :status and runStatus = , status = (int)BasicStatus.有效, runStatus = (int)RunStatus.启用
                    var result = con.QueryFirst<RuleConfig>("SELECT * FROM RULECONFIG where uniqueCode = :uniqueCode ", new { uniqueCode });
                    if(result == null) {
                        Logger.Error($"RuleConfig表中UniqueCode为{uniqueCode}的接口配置不可使用，请检查配置");
                        return;
                    }
                    if(result.Status == (int)BasicStatus.作废 || result.RunStatus == (int)RunStatus.停用) {
                        Logger.Error($"RuleConfig表中UniqueCode为{uniqueCode}，该调度已被停用或者作废，请重启调度服务或者恢复调度配置以保证正常调度");
                        return;
                    }
                    if(result.IsWebService == (int)YesOrNo.是 && result.IsAuthentication == (int)YesOrNo.是) {
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        var executeMsg = HttpUtils.PostWebServiceWithCredential(result.Address, result.PostBody, result.UserName, result.Password);
                        stopwatch.Stop();
                        var executeTime = stopwatch.Elapsed.TotalSeconds;
                        con.Execute(@"insert into monitorlogrecord(id,ruleconfigid,message,createtime,executetime,operationType,statusCode,statusCodeDescription,responseMessage) values(s_monitorlogrecord.nextval,:ruleconfigid,:message,sysdate,:executetime,:operationType,:statusCode,:statusCodeDescription,:responseMessage)", new { RuleconfigId = result.Id, Message = executeMsg.Message, ExecuteTime = executeTime, OperationType = executeMsg.Status, executeMsg.StatusCode, executeMsg.StatusCodeDescription, executeMsg.ResponseMessage });
                    }
                    if(result.IsWebService == (int)YesOrNo.是 && result.IsAuthentication == (int)YesOrNo.否) {
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        var executeMsg = HttpUtils.PostWebServiceWithoutCredential(result.Address, result.PostBody);
                        stopwatch.Stop();
                        var executeTime = stopwatch.Elapsed.TotalSeconds;
                        con.Execute(@"insert into monitorlogrecord(id,ruleconfigid,message,createtime,executetime,operationType,statusCode,statusCodeDescription,responseMessage) values(s_monitorlogrecord.nextval,:ruleconfigid,:message,sysdate,:executetime,:operationType,:statusCode,:statusCodeDescription,:responseMessage)", new { RuleconfigId = result.Id, Message = executeMsg.Message, ExecuteTime = executeTime, OperationType = executeMsg.Status, executeMsg.StatusCode, executeMsg.StatusCodeDescription, executeMsg.ResponseMessage });
                    }
                    if(result.IsWebService == (int)YesOrNo.否 && result.IsAuthentication == (int)YesOrNo.是) {
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        var executeMsg = HttpUtils.GetWithCredential(result.Address, result.PostBody, result.UserName, result.Password);
                        stopwatch.Stop();
                        var executeTime = stopwatch.Elapsed.TotalSeconds;
                        con.Execute(@"insert into monitorlogrecord(id,ruleconfigid,message,createtime,executetime,operationType,statusCode,statusCodeDescription,responseMessage) values(s_monitorlogrecord.nextval,:ruleconfigid,:message,sysdate,:executetime,:operationType,:statusCode,:statusCodeDescription,:responseMessage)", new { RuleconfigId = result.Id, Message = executeMsg.Message, ExecuteTime = executeTime, OperationType = executeMsg.Status, executeMsg.StatusCode, executeMsg.StatusCodeDescription, executeMsg.ResponseMessage });
                    }
                    if(result.IsWebService == (int)YesOrNo.否 && result.IsAuthentication == (int)YesOrNo.否) {
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();
                        var executeMsg = HttpUtils.GetWithoutCredential(result.Address, result.PostBody);
                        stopwatch.Stop();
                        var executeTime = stopwatch.Elapsed.TotalSeconds;
                        con.Execute(@"insert into monitorlogrecord(id,ruleconfigid,message,createtime,executetime,operationType,statusCode,statusCodeDescription,responseMessage) values(s_monitorlogrecord.nextval,:ruleconfigid,:message,sysdate,:executetime,:operationType,:statusCode,:statusCodeDescription,:responseMessage)", new { RuleconfigId = result.Id, Message = executeMsg.Message, ExecuteTime = executeTime, OperationType = executeMsg.Status, executeMsg.StatusCode, executeMsg.StatusCodeDescription, executeMsg.ResponseMessage });
                    }
                }
            }, context.CancellationToken);
        }
    }
}
